#!/usr/bin/env python

import sys
import re

TASKS = 0
ISRS = 1
SEMAS = 2
QUEUES = 3
EVENTS = 4
NOTES = 7
AGENTS = 8

ids = []

def main():

   if len(sys.argv) == 3:

      f = open(sys.argv[1])

      for line in f:

         if line.startswith('NAM'):

            rm = 'NOTES' in sys.argv[2] and int(line.split()[1]) == NOTES
            rm = rm or 'TASKS' in sys.argv[2] and int(line.split()[1]) == TASKS

            if re.search(sys.argv[2], line) or rm:

               id = int(line.split()[2])
               if not id in ids:
                  ids.append(id)
                  sys.stderr.write('removing : %s\n' % line[:-1])

            else:
               print line,

         elif line.startswith('STA') or line.startswith('STO') or line.startswith('OCC'):
            if not int(line.split()[2]) in ids:
               print line,

         elif line.startswith('DSC'):
            if not re.search(sys.argv[2], line):
               print line,

         else:
            print line,

      f.close()

   else:
      print("Usage: %s tdifile pattern" % sys.argv[0])

if __name__ == "__main__":
   main()
